<template>
  <t-card title="商品列表" :bordered="false">
    <template #actions>
      <t-button variant="text" theme="default" @click="router.push('/merchant/goods/trash')">
        <template #icon><t-icon name="delete" /></template>
        回收站
      </t-button>
    </template>
    <div class="category-header c-flex">
      <div class="l">
        <t-button theme="primary" @click="router.push('/merchant/goods/add')"> 添加 </t-button>
      </div>
      <div class="r c-flex">
        <t-space>
          <t-select v-model="params.cate_id" :clear="fetchData" empty="没有分类" placeholder="全部分类" type="search" clearable :options="categoryList" />
          <t-input v-model="params.name" placeholder="请输入商品名" clearable>
            <template #suffix-icon>
              <t-icon name="search" />
            </template>
          </t-input>
          <t-button theme="primary" @click="searchData">查询</t-button>
        </t-space>
      </div>
    </div>
    <t-base-table :data="lists" :columns="COLUMNS" row-key="id" vertical-align="middle" :hover="lists?.length > 0 ? true : false" :pagination="pagination" :loading="dataLoading" :header-affixed-top="headerAffixedTop" table-layout="auto" max-height="100%" @page-change="rehandlePageChange">
      <template #name="{ row }">
        <t-space direction="vertical" size="small" class="tag-demo light">
          <span>
            {{ row.name }}
            <t-tag v-if="row.wholesale_discount == 1" title="支持批发优惠" theme="success" variant="light" size="small" shape="round">惠</t-tag>
            <t-tag v-if="row.coupon_type == 1" title="支持优惠券" theme="primary" variant="light" size="small" shape="round">券</t-tag>
            <t-tag v-if="row.take_card_type != 0" title="提卡必填或选填取卡密码" theme="warning" variant="light" size="small" shape="round">取</t-tag>
            <t-tag v-if="row.visit_type == 1" title="商品购买页面需要访问密码" theme="danger" variant="light" size="small" shape="round">密</t-tag>
          </span>
        </t-space>
      </template>
      <template #status="{ row }">
        <t-switch v-model="row.status" :custom-value="[1, 0]" @click="changeStatus(row.id, row.status)"> </t-switch>
      </template>
      <template #create_at="{ row }">
        <span>{{ formatTime(row.create_at) }}</span>
      </template>

      <template #operation="{ row }">
        <t-space>
          <t-link theme="primary" hover="color" @click="showGoodLink(row)">链接</t-link>
          <t-link theme="primary" hover="color" @click="router.push(`/merchant/goods/card/add?goods_id=${row.id}`)">加库存</t-link>
          <t-link theme="primary" hover="color" @click="editRow(row)">编辑</t-link>
          <t-link theme="danger" hover="color" @click="delRow(row)">删除</t-link>
        </t-space>
      </template>
      <template #empty>
        <result title="" tip="暂无相关数据" type="list"> </result>
      </template>
    </t-base-table>
    <t-loading :loading="loading" size="small" fullscreen />
    <good-link ref="goodLinkRef" />
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'Goods',
};
</script>

<script setup lang="ts">
import { MessagePlugin } from 'tdesign-vue-next';
import { nextTick, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { listSimple } from '@/api/merchant/goods/category';
import { list, status } from '@/api/merchant/goods/good';
import Result from '@/components/result/index.vue';
import { table } from '@/hooks/table';
import { useBatchAction } from '@/hooks/useBatchAction';
import { formatTime } from '@/utils/date';

import GoodLink from './components/GoodsLink.vue';
import { COLUMNS } from './constant';

const router = useRouter();
const params = reactive({
  cate_id: null,
  name: '',
});
const { query } = router.currentRoute.value as any;
if (query.cate_id) {
  params.cate_id = +query.cate_id;
}

const { pagination, fetchData, dataLoading, headerAffixedTop, rehandlePageChange, lists, searchData } = table({
  fetchFun: list,
  params,
});

const loading = ref(false);

const categoryList = ref([]);
const fetchGoodsCategory = async () => {
  const { data } = await listSimple();
  categoryList.value = data.list;
};
onMounted(() => {
  fetchData();
  fetchGoodsCategory();
});

// 查看商品链接
const goodLinkRef = ref();
const showGoodLink = async (row: any) => {
  await nextTick();
  goodLinkRef.value?.init(row.id);
};

const delRow = async (row: any) => {
  useBatchAction({
    title: '提醒',
    body: `是否确认删除(${row.name})？`,
    ids: row.id,
    url: '/merchantapi/goods/good/del',
    fetchList: () => {
      fetchData();
    },
  });
};

const changeStatus = async (id: any, val: any) => {
  try {
    const res = await status({
      id,
      val,
    });
    if (res.code === 1) {
      MessagePlugin.success(res.msg);
    } else {
      MessagePlugin.error(res.msg);
    }
  } catch (error) {
    MessagePlugin.error('修改失败');
  }
};

const editRow = (row: any) => {
  const { id } = row;
  router.push(`/merchant/goods/edit?id=${id}`);
};
</script>
